package com.sq.loginservice.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.sq.api.dto.SysUserDto;
import com.sq.api.user.UserServiceApi;
import com.sq.api.user.model.LoginUser;
import com.sq.common.constants.Constants;
import com.sq.common.exception.server.ServiceException;
import com.sq.common.utils.StringUtils;
import com.sq.common.utils.user.PasswordUtil;
import com.sq.common.utils.user.UserUtil;
import com.sq.common.web.R;
import com.sq.loginservice.service.LogService;
import com.sq.loginservice.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @Author Li sir
 * @Date 2024/9/30
 */

@Service
public class RegisterServiceImpl implements RegisterService
{

    @Autowired
    private UserServiceApi userServiceApi;

    @Autowired
    private LogService logService;

    @Override
    public int userRegister(SysUserDto sysUserDto) {
        String userName = sysUserDto.getUserName();
        String password = sysUserDto.getPassword();
        if (StringUtils.isAnyBlank(userName,password)){
            logService.saveLog(userName, Constants.LOGIN_FAIL,"用户/密码未填写");
            throw new ServiceException("用户/密码未填写");
        }

        // 校验username是否合法
        boolean okUserName = UserUtil.isOkUserName(userName);

        if (!okUserName){
            throw new ServiceException(userName + "是非法用户名");
        }

        // 校验密码
        boolean cheek = PasswordUtil.cheekPasswordLen(password);
        if (!cheek){
            throw new ServiceException("密码长度小于" + PasswordUtil.passlen + "位");
        }
        boolean passSafe = PasswordUtil.cheekPassSafe(password);

        if (!passSafe){
            throw new ServiceException("当前密码不符合规范");
        }
        // 查询用户信息是否存在,存在则报错
        R result = userServiceApi.existUser(userName);

        int code = result.getCode();

        if (!Constants.FAIL.equals(code)){
            throw new ServiceException(userName + "被注册");
        }

        String randomSaft = PasswordUtil.getRandomSaft(6);
        String safePassword = SaSecureUtil.aesEncrypt(randomSaft, password);
        sysUserDto.setSalt(randomSaft);
        sysUserDto.setPassword(safePassword);
        sysUserDto.setCreateTime(new Date());
        R<Integer> integerR = userServiceApi.registerUser(sysUserDto);
        if (Constants.FAIL.equals(integerR.getCode())){
            throw new ServiceException(integerR.getMsg());
        }
        return integerR.getData();
    }
}
